//
//  RootViewController.m
//  RepasoApp
//
//  Created by Vicente Vicens Camarena on 02/10/11.
//  Copyright 2011 Imathink World, S.L.N.E. All rights reserved.
//

#import "RootViewController.h"

#import "DetailViewController.h"
#import "CourseViewController.h"
#import "Teacher.h"
#import "Course.h"
#import "Resource.h"

#define REMOTE_PLIST @"http://www.kankiu.com/api/all.php"


@interface RootViewController ()

@property (nonatomic, retain) NSMutableArray *teachers;
@property (nonatomic, retain) NSString * localCoursesPath;
@property (nonatomic, retain) NSMutableData * data;

- (void)loadLocalCursos;
- (void)loadRemoteCursos;
- (BOOL)haveCachedCursos;
- (void) saveCourses: (NSArray *) rootDictionaries;

- (void) stopIndicator;
- (void) startIndicator;
- (void) startIndicatorWithMessage: (NSString *) message;
- (void) startProgressIndicatorWithMessage: (NSString *) message withProgress: (float) progress;
- (void) changeIndicatorMessage: (NSString *) message;
- (void) changeProgressIndicatorWithMessage: (NSString *) message withProgress: (float) progress;

- (void) showError: (NSString *) message ;
@end

@implementation RootViewController
		
@synthesize detailViewController;
@synthesize teachers = teacher_;
@synthesize localCoursesPath;
@synthesize data;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.clearsSelectionOnViewWillAppear = NO;
    self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
    
    self.title = NSLocalizedString(@"Clases", @"");
    
        
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    self.localCoursesPath = [documentsDirectory stringByAppendingPathComponent: @"courses.plist"];
    
    
    self.tableView.rowHeight = 60.0;
    
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:41.0/255.0 green:136.0/255.0 blue:145.0/255.0 alpha:1.0];

    if ([self haveCachedCursos]){
        [self loadLocalCursos];
    }
    
    [self loadRemoteCursos];
}

		
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.teachers count];
    		
}

		
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    Teacher *selectedTeacher = [self.teachers objectAtIndex:section];
    
    return [selectedTeacher.teacherCourses count];
    		
}

		
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    Teacher *selectedTeacher = [self.teachers objectAtIndex:indexPath.section];
    Course *selectedCourse = [selectedTeacher.teacherCourses objectAtIndex:indexPath.row];
    
    cell.textLabel.text = selectedCourse.courseTitle;
    cell.detailTextLabel.text = selectedCourse.courseDescription;
    cell.imageView.image = selectedCourse.courseImage;
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    Teacher *selectedTeacher = [self.teachers objectAtIndex:section];
    
    return selectedTeacher.teacherName;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here -- for example, create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    CourseViewController *courseViewController = [[CourseViewController alloc] initWithNibName:nil bundle:nil];
    Teacher *selectedTeacher = [self.teachers objectAtIndex:indexPath.section];
    courseViewController.course = [selectedTeacher.teacherCourses objectAtIndex:indexPath.row];
    courseViewController.detailViewController = self.detailViewController;
    [self.navigationController pushViewController:courseViewController animated:YES];
    [courseViewController release];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)loadRemoteCursos{
    NSURLRequest * request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:REMOTE_PLIST] cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 60];
	NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	[request release];

    self.data = [[[NSMutableData alloc] init]autorelease];

	[self startIndicatorWithMessage: @"Cargando cursos"];
}



- (void) connection: (NSURLConnection *) connection didReceiveResponse: (NSURLResponse *) response{
	[self.data setLength:0];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)moreData{
	[self.data appendData:moreData];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [self stopIndicator];
    if (![self haveCachedCursos]){
        [self showError: NSLocalizedString(@"Error al cargar la información de los cursos",nil)];
    }

}



- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    
    NSString * errorString;
	NSArray * coursesDictionaries = [[NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:nil errorDescription:&errorString] retain];
    [self saveCourses: coursesDictionaries];
    
    //Lo guardo en caché para próximas ocasiones
    [data writeToFile:self.localCoursesPath atomically:NO];
    
	[data release];
    
	 
	[self.tableView reloadData];
}


- (void)loadLocalCursos{
    NSArray *rootDictionaries = [NSArray arrayWithContentsOfFile:self.localCoursesPath];
    [self saveCourses: rootDictionaries];
    
    [self.tableView reloadData];
    
}

- (void) saveCourses: (NSArray *) rootDictionaries{
    self.teachers = [NSMutableArray arrayWithCapacity:[rootDictionaries count]];
    for (NSDictionary *teacherDictionary in rootDictionaries) {
        [self.teachers addObject:[Teacher teacherWithDictionary:teacherDictionary]];
    }
    
    //Ahora descargo uno por uno todos los ficheros
    
    
    NSMutableArray * genericDownloadItems = [[[NSMutableArray alloc] init] autorelease];
    for (Teacher * teacher in self.teachers) {
        for (Course * course in teacher.teacherCourses){
            for (Resource * resource in course.courseResources){
                if ([resource isCached]){
                    continue;
                }
                
                GenericDownloadItem * genericDownloadItem = [[[GenericDownloadItem alloc] init] autorelease];
                genericDownloadItem.downloadPath = resource.resourceURL;
                genericDownloadItem.cachePath = [resource localPath];
                
                //            NSLog(@"URL: %@", resource.resourceURL);
                //            NSLog(@"Local Path: %@", [resource localPath]);
                
                
                [genericDownloadItems addObject: genericDownloadItem];
            }
        }
    }
    
    if ([genericDownloadItems count] > 0){
        GenericDownloader * genericDownloader = [[[GenericDownloader alloc] init] autorelease];
        genericDownloader.downloadItems = genericDownloadItems;
        genericDownloader.downloadDelegate = self;
        [genericDownloader startDownload];
        
        [self startProgressIndicatorWithMessage:[NSString stringWithFormat: @"Descargando %d de %d elementos", 0, [genericDownloadItems count]] withProgress:0];
    }
    else{
        [self stopIndicator];
    }
   
        
}




- (BOOL)haveCachedCursos{
    return [[NSFileManager defaultManager] fileExistsAtPath:self.localCoursesPath];
}


- (void) showError: (NSString *) message 
{
         
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"ERROR",nil)
                                                         message: message
                                                        delegate: nil 
                                               cancelButtonTitle: NSLocalizedString(@"Aceptar",nil) 
                                               otherButtonTitles: nil];
    [alertView show];
    [alertView release];
}


- (void) genericDownloaderStarted: (int) aNumItemsToDownload{
    numItemsToDownload = aNumItemsToDownload;
    [self startProgressIndicatorWithMessage:[NSString stringWithFormat: @"Descargando %d de %d elementos", 0, numItemsToDownload] withProgress:0];
}

- (void) genericDownloaderProcessChanged: (int) numItemsDownloaded{
    [self startProgressIndicatorWithMessage:[NSString stringWithFormat: @"Descargando %d de %d elementos", numItemsDownloaded,numItemsToDownload] withProgress:numItemsDownloaded/(float)numItemsToDownload];
}

- (void) genericDownloaderItemDownloadSuccess: (GenericDownloadItem *) downloadItem{
    
}

- (void) genericDownloaderItemDownloadError: (GenericDownloadItem *) downloadItem{
    
}

- (void) genericDownloaderFinished{
    [self stopIndicator];
}

- (void) genericDownloaderError: (NSString *) message{
    
}

- (void) genericDownloaderFinishedWithNumErrors: (int) numErrors andNumItemsDownloaded: (int) numItemsDownloaded{
    [self stopIndicator];
    
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"ERROR",nil)
                                                         message: [NSString stringWithFormat:@"Falló la descarga de %d", numErrors]
                                                        delegate: nil 
                                               cancelButtonTitle: NSLocalizedString(@"Aceptar",nil)
                                               otherButtonTitles: nil];
    [alertView show];
    [alertView release];

}

- (void) genericDownloaderStopped{
    
}


//##########
//INDICATORS
//##########
- (void) stopIndicator{
	[progressHUD hide: YES];
}

- (void) startIndicatorWithMessage: (NSString *) message{
	if (progressHUD==nil){
		progressHUD = [[MBProgressHUD alloc] initWithView:self.detailViewController.view];
        [self.detailViewController.view addSubview: progressHUD];
	}
	progressHUD.mode = MBProgressHUDModeIndeterminate;
	progressHUD.labelText = message;
	//progressHUD.mode
	
    [progressHUD show: YES];
	
}

- (void) changeIndicatorMessage: (NSString *) message{
    progressHUD.labelText = message;
}

- (void) startIndicator{
	[self startIndicatorWithMessage:@""];
	
}

- (void) startProgressIndicatorWithMessage: (NSString *) message withProgress: (float) progress{
	if (progressHUD==nil){
		progressHUD = [[MBProgressHUD alloc] initWithView:self.detailViewController.view];
        [self.detailViewController.view addSubview: progressHUD];
	}
	
    progressHUD.mode = MBProgressHUDModeDeterminate;
	progressHUD.labelText = message;
	progressHUD.progress = progress;
	
    [progressHUD show: YES];
	
}


- (void) changeProgressIndicatorWithMessage: (NSString *) message withProgress: (float) progress{
    progressHUD.progress = progress;
    progressHUD.labelText = message;
}


- (void)dealloc
{
    [teacher_ release];
    [detailViewController release];
    [activityAlert release];
    [progressHUD release];
    [super dealloc];
}

@end
